// ajax
function doAjax({ url, data = {}, method, sucCallback, failCallback, failDuration = 4 }) {
  return new window.Promise(function (resolve, reject) {
    $.ajax({
      url: url,
      headers: {
        'iBox': 'ajax',
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      data: data,
      type: method,
      dataType: 'json',
    }).done(function (msg) {
      if (msg.code !== 0) {
        Shield && Shield.vNotify.error({
          title: '',
          content: msg.message,
          duration: failDuration,
        });
        if (401 == msg.code) {
          setTimeout(function () {
            window.location.href = msg.data.url;
          }, 1500);
        }
        failCallback && failCallback(msg);
        return reject({ code: msg.code, data: msg.data, message: msg.message });
      } else {
        sucCallback && sucCallback(msg.data);
        return resolve(msg.data);
      }
    }).fail(function (error) {
      Shield && Shield.vNotify.error({
        title: '',
        content: '服务器返回错误，数据无法加载。'
      });
      failCallback && failCallback();
      return reject({ code: 503, message: '服务器返回错误，数据无法加载。' });
    });
  });
}

function doAjaxWithFile({ url, data = {}, method, sucCallback, failCallback, failDuration = 4 }) {
  return new window.Promise(function (resolve, reject) {
    $.ajax({
      url: url,
      data: data,
      type: method,
      contentType: false,
      processData: false,
      dataType: 'json'
    }).done(function (msg) {
      if (msg.code !== 0) {
        Shield && Shield.vNotify.error({
          title: msg.message,
          duration: failDuration,
        });
        if (401 == msg.code) {
          setTimeout(function () {
            window.location.href = msg.data.url;
          }, 1500);
        }
        failCallback && failCallback(msg);
        return reject({ code: msg.code, data: msg.data, message: msg.message });
      } else {
        sucCallback && sucCallback(msg.data);
        return resolve(msg.data);
      }
    }).fail(function (error) {
      Shield && Shield.vNotify.error('服务器返回错误，数据无法加载。');
      failCallback && failCallback();
      return reject({ code: 503, message: '服务器返回错误，数据无法加载。' });
    });
  });
}

export {
  doAjax,
  doAjaxWithFile
};